package com.jtw.common.util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Xml2JsonUtil {
	
	public static void main(String[] args) {
		String xml = "<xml><appid><![CDATA[wxafa7be2ea5cd85ea]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1298718701]]></mch_id><nonce_str><![CDATA[069d3bb002acd8d7dd095917f9efe4cb]]></nonce_str><openid><![CDATA[ojfX5t4_fxhkuHt5UWcx0iV2Ylrg]]></openid><out_trade_no><![CDATA[155]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[8207D65EF63940D81FE4A6F299403943]]></sign><time_end><![CDATA[20151228120949]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[APP]]></trade_type><transaction_id><![CDATA[1001830243201512282360533117]]></transaction_id></xml>";
		Map<String, Object> map = xmlStrToMap(xml);
		System.out.println(map.get("result_code"));               
		System.out.println(map.get("out_trade_no"));
		System.out.println(map.get("transaction_id"));
	}
	
	public static Map<String, Object> xmlStrToMap(String xmlStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Document doc = DocumentHelper.parseText(xmlStr);
            Element root = doc.getRootElement();
            List<?> children = root.elements();
            if(children != null && children.size() > 0) {
                for(int i = 0; i < children.size(); i++) {
                    Element child = (Element)children.get(i);
                    map.put(child.getName(), child.getTextTrim());
                }
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return map;  
    }
}
